﻿#region - Legal -

/*
Copyright © 2011, Tateeda Media Network
All rights reserved. http://tateeda.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither the name of the Tateeda Media Network, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

#endregion - Legal -

using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Concrete.Services;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Interfaces.Services;
using Tateeda.ClinicalStudy.Base.Modules.Models.StudyVisit;
using Tateeda.ClinicalStudy.Base.Modules.Models.User;
using Tateeda.ClinicalStudy.Base.Web.Common;

namespace Tateeda.ClinicalStudy.Base.Web.Controllers {

    public class SchedulerController : Controller {
        readonly ISchedulingService _service;
        readonly UserService _userService = new UserService();

        public SchedulerController(ISchedulingService service) {
            _service = service;
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult Index() {
            return View();
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult LoadCalendarEvents(double start, double end) {
            DateTime startDate = ConvertFromUnixTimestamp(start);
            DateTime endDate = ConvertFromUnixTimestamp(end);

            var appUser = _userService.FindUserByName(User.Identity.Name);
            var calAppointments = _service.GetCalendarAppointmentsBySite(appUser, startDate, endDate);

            var rows = calAppointments.ToArray();
            return Json(rows, JsonRequestBehavior.AllowGet);
        }

        //[OutputCache(Duration = 10)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult GetCalendarSiteSubjects() {
            var appUser = _userService.FindUserByName(User.Identity.Name);
            var subs = _service.GetActiveSubjectsForSiteFast(appUser.SiteId);
            return Json(subs);
        }

        //[OutputCache(Duration = 600)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult GetSiteAppUsers() {
            var appUser = _userService.FindUserByName(User.Identity.Name);
            var appUsers = _userService.GetSiteUsers(appUser.SiteId);
            var users = appUsers.Select(u => new AppUserModel { AppUserId = u.AppUserId, FirstName = u.FirstName, LastName = u.LastName }).ToList();

            return Json(users);
        }

        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        public JsonResult LoadAvailableVisitsForSubject(int subjectId) {
            var visits = _service.GetAvailableVisitsForSubject(subjectId);
            var visitsList = visits.Select(v => new VisitModel { Name = v.Name, VisitId = v.VisitId }).ToList();
            return Json(visitsList);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public void UpdateAppointment(int apointmentId, string title, string startTime, string endTime) {
            //! Incoming dates are UTC Formatted
            var start = GetDateTimeFromString(startTime);

            var end = start.AddHours(2);
            end = GetDateTimeFromString(endTime);
            _service.UpdateAppointment(apointmentId, title, start, end);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult CreateAppointment(string title, string start, string end, bool allDay, string description, int subject, int appUser, int visit) {
            var startTime = GetDateTimeFromString(start);
            var endTime = GetDateTimeFromString(end);
            string by = User.Identity.Name;
            var newId = _service.CreateAppointment(subject, visit, appUser, title, startTime, endTime, description, by);
            return Json(newId.ToString());
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult DeleteAppointment(int appointmentId) {
            return Json(_service.DeleteAppointment(appointmentId));
        }

        private static DateTime ConvertFromUnixTimestamp(double timestamp) {
            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return origin.AddSeconds(timestamp);
        }

        private DateTime GetDateTimeFromString(string dateIn) {
            const string formatString = "ddd, dd MMM yyyy HH:mm:ss UTC";
            const string format2 = "ddd, d MMM yyyy HH:mm:ss UTC";
            var date = DateTime.UtcNow;
            try {
                date = DateTime.ParseExact(dateIn, format2, CultureInfo.CurrentUICulture);
            } catch {
                try {
                    date = DateTime.ParseExact(dateIn, formatString, CultureInfo.CurrentUICulture);
                } catch {
                }
            }
            return date;
        }
    }
}